const global = {}

window.addEventListener('load', function() {
    const authorizeBtn = document.querySelector('#authorize')
    const startBtn = document.querySelector('#start')
    const stopBtn = document.querySelector('#stop')
    const uploadBtn = document.querySelector('#upload')
    const oTitle = document.querySelector('#title')
    let chunks = []

    function onSuccess(stream) {
        console.log(stream)
        alert("用户已经授权使用，麦克风，可以正常进行")

        const mediaRecorder = new MediaRecorder(stream)

        authorizeBtn.disabled = true
        startBtn.disabled = false

        startBtn.addEventListener('click', function () {
            chunks = []
            startBtn.disabled = true
            stopBtn.disabled = false
            mediaRecorder.start(1_000)

            mediaRecorder.addEventListener('dataavailable', function(e) {
                chunks.push(e.data)
            })

            mediaRecorder.addEventListener('stop', function() {
                let oAdudio = document.querySelector('audio')
                let blob = new Blob(chunks, {type: 'audio/ogg; codecs=opus'})
                let audioURL = window.URL.createObjectURL(blob)
                oAdudio.src = audioURL

                uploadBtn.addEventListener('click', function() {
                    let title = oTitle.value.trim()
                    let xhr = new XMLHttpRequest()
                    xhr.open('post', `/studio/track/record.json?title=${title}&type=audio/ogg; codecs=opus`);
                    xhr.onload = function () {
                        console.log(this.responseText)
                        try {
                            let data = JSON.parse(this.responseText)
                            if (data.result) {
                                location.assign('/studio/track/list.html')
                            } else {
                                location.assign('/studio/user/login.html')
                            }
                        } catch (e) {
                            alert("响应不是一个合法的 JSON 格式")
                            console.error(e)
                        }
                    }
                    xhr.send(blob)
                })

                stopBtn.disabled = true
                uploadBtn.disabled = false
            })
        })

        stopBtn.addEventListener('click', function() {
            mediaRecorder.stop()
        })
    }

    function onError(e) {
        console.log(e)
        alert("用户没有授权使用麦克风，结束录制")
    }

    authorizeBtn.addEventListener('click', function() {
        if (!navigator.mediaDevices.getUserMedia) {
            alert("浏览器不支持录制声音，请更换 Chrome 浏览器")
            return
        }

        const constraints = { audio: true }
        navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError)
    })
})